package com.tuojian.nanjing.healthysystem.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuojian.nanjing.healthysystem.entity.CheckIn;
import com.tuojian.nanjing.healthysystem.mapper.CheckInMapper;
import com.tuojian.nanjing.healthysystem.service.CheckInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements CheckInService {

    @Autowired
    private CheckInMapper checkInMapper;

    @Override
    @Transactional
    public CheckIn doCheckIn(Long userId) {
        LocalDate today = LocalDate.now();
        CheckIn existing = checkInMapper.selectByUserIdAndDate(userId, today);
        if (existing != null) {
            throw new RuntimeException("今日已打卡！");
        }
        CheckIn checkIn = new CheckIn();
        checkIn.setUserId(userId);
        checkIn.setCheckInDate(today);
        checkIn.setCompleted(true);
        this.save(checkIn); // 调用 MP 的 save()
        return checkIn;
    }

    @Override
    public List<CheckIn> getCheckInHistory(long userId, LocalDate from, LocalDate to) {
        return this.lambdaQuery()
                .eq(CheckIn::getUserId,userId)
                .ge(CheckIn::getCheckInDate,from)
                .le(CheckIn::getCheckInDate,to)
                .orderByAsc(CheckIn::getCheckInDate)
                .list();
    }

}
